package utility.connection;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpConnector {

	public String doPost(String url, HttpParameters parameters) {
		try {
			URL httpURL = new URL(url);
			return doRequest(httpURL, parameters, "POST");
		} catch (MalformedURLException e) {
			return "";
		}
	}

	public String doRequest(URL url, HttpParameters parameters, String method) {
		StringBuffer result = new StringBuffer();
		int responseCode = 200;
		try {
	        String data = parameters.asEncodedData();
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setInstanceFollowRedirects(false);
			conn.setDoOutput(true);
			conn.setRequestMethod(method);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();

			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				result.append(line);
				result.append("\n");
			}
			wr.close();
			rd.close();
			responseCode = conn.getResponseCode();	        
	    } catch (Exception e) {
	    	return result.toString();
	    }

		if(responseCode<300)return result.toString();
		
		return "";
	}

	public String doGet(String url, HttpParameters parameters) {
		try {
			URL httpURL = new URL(url);
			return doRequest(httpURL, parameters, "GET");
		} catch (MalformedURLException e) {
			return "";
		}
	}

}
